package cn.ratel.learn.act;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.LockSupport;

/**
 * Created by iver
 */
public class MainWaitForSubThread {
	static class Sub extends Thread {
		@Override
		public void run() {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("sub over");
		}
	}

	static class Sub1 extends Thread {
		@Override
		public void run() {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("sub1 over");
		}
	}

	static class Sub2 extends Thread {
		@Override
		public void run() {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("sub2 over");
			flag = false;
		}
	}

	static class Sub3 extends Thread {
		@Override
		public void run() {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("sub3 over");
			synchronized (lock){
				lock.notifyAll();
			}
		}
	}
	static class Sub4 extends Thread {
		Thread thread;
		Sub4(Thread thread) {
			this.thread = thread;
		}

		@Override
		public void run() {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("sub4 over");
			LockSupport.unpark(thread);
		}
	}
	static class Sub5 extends Thread {
		@Override
		public void run() {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("sub5 over");

//			countDownLatch.countDown();

//			try {
//				cyclicBarrier.await();
//			} catch (InterruptedException | BrokenBarrierException e) {
//				e.printStackTrace();
//			}

			semaphore.release();
		}
	}


	static volatile boolean flag = true;
	final static Object lock = new Object();
	final static CountDownLatch countDownLatch = new CountDownLatch(1);
	final static CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
	final static Semaphore semaphore = new Semaphore(1);

	public static void main(String[] args) throws Exception {
//		new Sub().start();

		// join
//		Sub1 sub = new Sub1();
//		sub.start();
//		sub.join();

		// 自旋
//		new Sub2().start();
//		while(flag){
//			Thread.sleep(1);
//		}

		// wait main, notify main
//		synchronized(lock){
//			new Sub3().start();
//			lock.wait();
//		}

		// LockSupport
//		new Sub4(Thread.currentThread()).start();
//		LockSupport.park();

		// CountDownLatch, CyclicBarrier, Semaphore
		new Sub5().start();
//		countDownLatch.await();
//		cyclicBarrier.await();
		semaphore.acquire();
		semaphore.acquire();
		

		System.out.println("main over..............");
	}
}
